package org.walkerljl.config.impl.readonly;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.walkerljl.commons.exception.AppException;
import org.walkerljl.commons.util.PropertiesUtils;
import org.walkerljl.config.abstracts.AbstractConfigurator;
import org.walkerljl.log.Logger;
import org.walkerljl.log.LoggerFactory;

/**
 * 基于JAVA Properties文件的只读配置器<br>
 * <li> 只在创建配置器的时候获取Properties的配置数据
 *
 * @author lijunlin
 */
public class PropertiesReadonlyConfigurator extends AbstractConfigurator {

	private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesReadonlyConfigurator.class);
	
	private Map<String, String> propertiesMap = new HashMap<String, String>();
	
	/**
	 * 构造函数
	 * @param propertiesFile
	 */
	public PropertiesReadonlyConfigurator(String propertiesFile) {
		load(propertiesFile);
	}
	
	@Override
	public Object getProperty(String key) {
		return propertiesMap.get(key);
	}
	
	/**
	 * 加载配置
	 * @param propertiesFile
	 * @throws IOException
	 */
	private void load(String propertiesFile) {
		InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
		Properties properties = null;
		try {
			properties = PropertiesUtils.createFromInputStream(ins);
		} catch (Exception e) {
			String errMsg = String.format("%s无法加载配置文件:%s, 异常信息:%s", getClass(), propertiesFile, e.getMessage());
			LOGGER.error(e.getMessage(), e);
			throw new AppException(errMsg, e);
		}
		if (properties == null) {
			return;
		}
		for (String key : properties.stringPropertyNames()) {
			String value = properties.getProperty(key);
			if (value == null || "".equals(value)) {
				continue;
			}
			propertiesMap.put(wrapKey(key), value);
		}
	}
}